
<template>
  <div class="content_index">
    <div class="ci_header">
      <div class="ci_left sec-title">
        <el-icon
          style="vertical-align: middle; display: unset; cursor: pointer"
          @click="backList()"
          ><Back
        /></el-icon>
        <span>{{ isEdit ? "编辑CPT" : "创建CPT" }}</span>
      </div>
    </div>
    <div class="ci_content" style="margin: 12px 16px">
      <el-form
        :model="form"
        ref="cptFormRef"
        :rules="cptFormRefRules"
        label-width="120px"
        style="width: 100%"
      >
        <el-form-item label="CPT名称：" prop="title">
          <el-input
            v-model.trim="form.title"
            placeholder="请输入CPT名称"
          />
        </el-form-item>
        <el-form-item label="CPT类型：" prop="type">
          <el-select
            :disabled="isEdit"
            v-model="form.type"
            clearable
            placeholder="请选择CPT类型"
            style="width: 100%"
          >
            <el-option label="lite" value="00" />
          </el-select>
        </el-form-item>
        <el-form-item label="签名类型：" prop="proofType">
          <el-select
            :disabled="isEdit"
            v-model="form.proofType"
            clearable
            placeholder="请选择签名类型"
            style="width: 100%"
          >
            <el-option label="Sm2p256v1" value="00" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述：" prop="description">
          <el-input
            type="textarea"
            v-model.trim="form.description"
            placeholder="请输入描述（150位字符以内）"
          />
        </el-form-item>
        <el-form-item label="CPT属性：" prop="properties">
          <el-row
            v-for="(item, index) in form.properties"
            :key="index + 1"
            style="width: 100%; border: 1px soild #dcdfe6"
          >
            <el-col :span="7">
              <el-form-item
                label="属性名"
                :prop="'properties.' + index + '.property'"
                :rules="{
                  max: 50,
                  required: true,
                  message: '请输入属性名，50字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                  type="text"
                  v-model.trim="item.property"
                  placeholder="请输入属性名"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item
                label="值类型"
                :prop="'properties.' + index + '.type'"
                :rules="{
                  required: true,
                  message: '请选择值类型',
                  trigger: 'blur',
                }"
              >
                <el-select
                  v-model.trim="item.type"
                  clearable
                  placeholder="请选择值类型"
                  style="width: 100%"
                >
                  <el-option label="string" value="00" />
                  <el-option label="number" value="01" />
                  <el-option label="boolean" value="02" />
                  <el-option label="datetime" value="03" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="描述"
                :prop="'properties.' + index + '.description'"
                :rules="{
                  max: 50,
                  required: true,
                  message: '限制50位字符以内',
                  trigger: 'blur',
                }"
              >
                <el-input
                type="text"
                  v-model.trim="item.description"
                  placeholder="请输入描述"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1" v-if="index !== 0">
              <el-icon class="delete_icon" @click="removeDomain(index)"
                ><Remove
              /></el-icon>
            </el-col>
            <el-col :span="1">
              <el-icon class="add_icon" @click="addDomain"
                ><CirclePlus
              /></el-icon>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="isLoading"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
    <script setup>
import { reactive, ref, onMounted, toRefs } from "vue";
import { useRouter, useRoute } from "vue-router";
import { CreateCPT, InfoCPT, EditCPT } from "@/api/CPT";
import { ElMessage } from "element-plus";
import {
  nameValidator,
} from "@/utils/validate";
const router = useRouter();
const route = useRoute();
const backList = () => {
  router.go(-1);
};
const isEdit = ref(false);
const isLoading = ref(false);
const cptFormRef = ref("form");
const form = reactive({
  title: "",
  type: "",
  proofType: "",
  description: "",
  properties: [
    {
      property: "",
      type: "",
      description: "",
    },
  ],
});
/** CPT名称校验 */
const validateCPTName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("CPT名称不能为空"));
  } else {
    // 校验昵称
    if (!nameValidator(value)) {
      rule.message =
        "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'";
      callback(new Error());
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
/** 表单校验规则 */
const cptFormRefRules = {
  title: [
    {
      required: true,
      validator: validateCPTName,
      message: "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'",
      trigger: "blur",
    },
    { max: 50, min: 2, message: "2-50位字符，不能以特殊字符及数字开头，只可包含特殊字符中的'.','_'或'-'", trigger: "blur" },
  ],
  type: [
    {
      required: true,
      message: "请选择CPT类型",
      trigger: "blur",
    },
  ],
  proofType: [
    {
      required: true,
      message: "请签名类型",
      trigger: "blur",
    },
  ],
  description: [
    { max: 150, message: "请输入描述(150个字符以内)", trigger: "blur" },
  ],
};
const onSubmit = () => {
  cptFormRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true;
      if (!isEdit.value) {
        let parmars = {
          cptJsonSchema: { ...form },
        };
        delete parmars.cptJsonSchema.did;
        CreateCPT(parmars)
          .then((res) => {
            if (res.success) {
              router.push({ path: "/CPTManagement/CPTList" });
              isLoading.value = false;
              ElMessage.success(res.msg || "CPT创建成功!");
            } else {
              ElMessage.error(res.msg || "CPT创建失败!");
              isLoading.value = false;
            }
          })
          .catch((err) => {
            ElMessage.error(err.msg || "CPT创建失败!");
            isLoading.value = false;
          });
      } else {
        let parmars = {
          cptId: route.query.id,
          cptJsonSchema: { ...form },
        };
        delete parmars.cptJsonSchema.did;
        EditCPT(parmars)
          .then((res) => {
            if (res.success) {
              router.push({ path: "/CPTManagement/CPTList" });
              isLoading.value = false;
              ElMessage.success(res.msg || "CPT编辑成功!");
            } else {
              ElMessage.error(res.msg || "CPT编辑失败!");
              isLoading.value = false;
            }
          })
          .catch((err) => {
            ElMessage.error(err.msg || "CPT编辑失败!");
            isLoading.value = false;
          });
      }
    } else {
      return false;
    }
  });
};
const addDomain = () => {
  if (form.properties.length > 9) {
    ElMessage.error("文件最多添加10条！");
    return false;
  }
  form.properties.push({
    property: "",
    type: "",
    description: "",
  });
};
const removeDomain = (index) => {
  if (index !== 0) {
    form.properties.splice(index, 1);
  }
};
const CPTInfo = () => {
  let cptId = route.query.id;
  InfoCPT(cptId)
    .then((res) => {
      if (res.success) {
        let cptForm = {
          ...res.data.cptJsonSchema,
          type: res.data.cptBaseInfo?.type,
          proofType: res.data.cptMetaData?.proofType,
        };
        Object.assign(form, cptForm);
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.msg);
    });
};
onMounted(() => {
  if (route.query.id) {
    isEdit.value = true;
    CPTInfo();
  } else {
    isEdit.value = false;
  }
});
</script>
    
    <style lang="scss" scoped>
@import "../../assets/css/cindex.scss";
:deep .el-upload-list--picture-card .el-upload-list__item-actions span + span {
  margin-left: 0.5em;
}
.add_icon {
  font-size: 18px;
  // margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.box {
  display: flex;
  .left_txContent {
    // width: 200px;
    width: 50%;
    padding: 20px;
    // height: 200px;
    // background: pink;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
    margin-right: 10px;
  }
  .rigth_txContent {
    width: 50%;
    padding: 20px;

    // width: 200px;
    // height: 200px;
    // background: red;
    border-radius: 8px;
    border: 1px solid #d6e9c6;
    word-break: break-word;
  }
}
.file_cn {
  // width: 130px;
  width: 100%;
  font-size: 14px;
  //   text-align: right;
  // margin-left: 70px;
  margin-bottom: 5px;
  padding: 10px;
  border-radius: 4px;
  border: 1px dashed #a6a6a6;
  div {
    margin-bottom: 15px;
  }
}
.Sign_content {
  display: flex;
  font-size: 14px;
  .Sign_content_key {
    display: inline-flex;
    justify-content: flex-end;
    align-items: flex-start;
    flex: 0 0 auto;
    height: 32px;
    line-height: 32px;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    width: 90px;
  }
  .Sign_content_data {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    line-height: 32px;
    position: relative;
    min-width: 0;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}

.red {
  color: red;
}
.green {
  color: green;
}
.el-form-item .el-form-item {
  width: 100%;
  margin-bottom: 20px;
}
.el-form-item .el-row {
  border: 1px soild #dcdfe6 !important;
  //   box-sizing: unset;
}
.wordWrap {
  word-break: break-word;
}
:deep .el-descriptions .el-descriptions__label {
  display: inline-block;
  width: 100px;
  text-align: right;
}
.add_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
.delete_icon {
  font-size: 18px;
  margin-left: 10px;
  cursor: pointer;
  height: 100%;
}
</style>